package com.iron.visual.codegen.controller;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iron.common.core.util.R;
import com.iron.visual.codegen.entity.GenConfig;
import com.iron.visual.codegen.service.SysGeneratorService;
import com.iron.visual.codegen.uitl.GenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * 代码生成器
 *
 * @author YT
 * @date 2019-06-18
 */
@Api(tags = "MySql 代码生成器")
@RestController
@AllArgsConstructor
@RequestMapping("/mySqlGenerator")
public class MySqlGeneratorController {

    private final SysGeneratorService mySqlGeneratorService;

    /**
     * 列表
     *
     * @param page
     * @param tableName 表名称
     * @return
     */
    @ApiOperation(value = "获取表字段列表", notes = "根据表名获取表字段列表")
    @ApiImplicitParam(paramType = "path", dataType = "String", name = "tableName", value = "表名")
    @GetMapping("/page")
    public R getPage(Page page, String tableName) {
        return R.ok(mySqlGeneratorService.getPage(page, tableName));
    }

    /**
     * 代码生成
     *
     * @param genConfig
     * @param response
     */
    @ApiOperation(value = "代码生成", notes = "配置代码生成类自动生成代码")
    @SneakyThrows
    @PostMapping("/code")
    public void generatorCode(@RequestBody GenConfig genConfig, HttpServletResponse response) {
        byte[] data = mySqlGeneratorService.generatorCode(genConfig);
        response = GenUtils.setZipResponse(response, data, genConfig.getTableName());
        IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
    }
}
